from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.urls import reverse
from openpyxl import Workbook,load_workbook
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from .models import *
import os
# Create your views here.


def entering(request):

    
    context = {}
    return render(request,'entering/entering.html',context)


def entering_yunsuan(request):
    info = request.FILES.get('excel')
    print(info)
    paper_name = request.POST['paper_name']
    if ExamName.objects.filter(exam_name = paper_name).exists():
        context = {'message_z':'试卷名字已存在！'}
        return render(request,'entering/entering.html',context)
    else:
        wb = load_workbook(info)
        sheet1 = wb['Sheet1']
        last_dict = {}
        max_row = sheet1.max_row
        for i in range(2,max_row+1):
            last_dict[sheet1['A{}'.format(i)].value]=sheet1['B{}'.format(i)].value
        
        if last_dict.keys() == '':
            context = {'message_k':'Excel内容为空！'}
            return render(request,'entering/entering.html',context)
        else:
            for key in last_dict.keys():
                stu_obj = StudentName(student_name = key)
                stu_obj.save()
                paper_obj = ExamName(exam_name = paper_name)
                paper_obj.save()
                stu_obj.examscore_set.create(exam_score=last_dict[key],exam=paper_obj)
        
                context = {'message':'保存成功'}
            return render(request,'entering/entering.html',context)
